const socket = require("socket.io");
const SimplePeer = require('simple-peer');

// const { PeerServer } = require('peer');
// const peerServer = PeerServer({ port: 9000, path: '/myPeerServer' });
// import { Peer } from 'peerjs';
// const { updateRoomCounts, updateAndBroadcastRoomCounts, getUsersInRoom } = require('./util/roomCounts.js');
const { extendIo } = require('./util/main.js')
module.exports = (server) => {
    const io = socket(server, {
        cors: {
            origin: "*",
        },
    });
    extendIo(io)

    let usersArr = [] //用户
    let chatArr = [] //聊天记录
    let rtcInfo = {
        stream: null,
        offer: null,
        answer: null
    }
    io.on('connection', (socket) => {
        const userInfo = socket.handshake.query
        const socketId = socket.id
        // 判断名字
        if (!userInfo && userInfo.userName === '' && !userInfo.userName) {
            console.log('用户信息不能为');
            socket.emit('error', {
                message: '用户信息不能为空'
            })
            // socket.disconnect()
            return
        }
        // console.log(userInfo);
        usersArr.push({ socketId, ...userInfo })
        const USERCOUNT = 5

        socket.on('join', (info) => {
            const room = info.roomId;
            // console.log('room', room);
            console.log('收到客户端加入房间请求', info);
            socket.join(room);

            sendRoomInfo(io, socket, room, usersArr)

            // console.log('io.sockets', io.sockets.adapter.rooms.get(room));

            var myRoom = io.sockets.adapter.rooms[room];
            var users = (myRoom) ? Object.keys(myRoom.sockets).length : 0;
            console.log(myRoom, users);
            //socket.emit('joined', room, socket.id); //发给自己
            //socket.broadcast.emit('joined', room, socket.id); //发给除自己之外的这个节点上的所有人
            //io.in(room).emit('joined', room, socket.id); //发给房间内的所有人
        });
        socket.on('message', (data) => {
            console.log('收到客户端的信息', data);
            chatArr.push(data);
            io.emit('message', chatArr);
        });



        socket.on('leave', (room) => {
            var myRoom = io.sockets.adapter.rooms[room];
            var users = (myRoom) ? Object.keys(myRoom.sockets).length : 0;
            logger.debug('the user number of room is: ' + (users - 1));
            //socket.emit('leaved', room, socket.id);
            //socket.broadcast.emit('leaved', room, socket.id);
            socket.to(room).emit('bye', room, socket.id);
            socket.emit('leaved', room, socket.id);
            //io.in(room).emit('leaved', room, socket.id);
        });


        socket.on('callRemote', (data) => {
            console.log('开始会议,邀请对方参加会议', data);
            let roomId = data.roomId
            socket.to(roomId).emit('callRemote', {
                message: '邀请您参加会议',
                code: 200
            })
        })
        socket.on('acceptCall', (data) => {
            console.log('收到同意邀请', data);
            console.log(data);
            let roomId = data.roomId
            socket.to(roomId).emit('acceptCall', {
                message: '对方接受了邀请',
                code: 200
            })
        })

        socket.on('sendOffer', (data) => {
            rtcInfo.offer = data.offer

            console.log('收到offer',);
            console.log(data);
            let roomId = data.roomId
            socket.to(roomId).emit('receiveOffer', {
                offer: data.offer,
                message: '接收了一份offer',
                code: 200
            })
        })
        socket.on('sendAnswer', (data) => {
            rtcInfo.answer = data.answer

            console.log('收到anwer', data);
            let roomId = data.roomId
            socket.to(roomId).emit('receiveAnswer', {
                answer: data.answer,
                message: '接收了一份answer',
                code: 200
            })
        })

        socket.on('sendCandidate', (data) => {
            console.log('收到Candidate', data);
            let roomId = data.roomId
            socket.to(roomId).emit('receiveCandidate', {
                candidate: data.candidate,
                message: '接收了一份candidate',
                code: 200
            })
        })

        // 监听断开连接事件
        socket.on('disconnect', () => {
            // 用户断开连接时，从映射表中移除对应的映射关系
            const disconnectedUser = usersArr.find(user => user.id === socket.id);
            if (disconnectedUser) {
                usersArr = usersArr.filter(user => user.id !== socket.id);
                // 从房间中移除断开连接的用户
                const rooms = Object.keys(socket.rooms);
                rooms.forEach(room => {
                    socket.to(room).emit('userLeft', disconnectedUser.userName);
                    socket.leave(room);
                });
                // 在这里可以执行其他处理逻辑，比如通知其他用户等操作
                console.log(`${disconnectedUser.userName} 断开连接`);
            }
        });

    });
}


// 发送有关的房间信息
function sendRoomInfo(io, socket, room, usersArr) {
    let roomsInfo = io.sockets.adapter.rooms
    let myRoom = Array.from(io.sockets.adapter.rooms.get(room));
    let results = []
    for (let i = 0; i < usersArr.length; i++) {
        for (let j = 0; j < myRoom.length; j++) {
            if (usersArr[i].socketId === myRoom[j]) {
                results.push(usersArr[i])
            }
        }
    }
    results = Array.from(new Set(results))
    let data = {
        roomId: room,
        roomsInfo,
        myRoom,
        results
    };

    io.emit('roomInfo', JSON.stringify(data));
}